package com.huilai.platform.country_platform.service;

import com.huilai.platform.country_platform.core.Result;
import com.huilai.platform.country_platform.core.ResultGenerator;
import com.huilai.platform.country_platform.model.User;
import com.huilai.platform.country_platform.repository.UserRepository;
import com.huilai.platform.country_platform.util.CookieUtil;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 作者：洪霓
 * 日期：2023/2/22
 * 注释：
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LoginService loginService;

    public User getUserByCookie(HttpServletRequest request) {
        Cookie cookie = CookieUtil.get(request, "username");
        User user = null;
        if (cookie == null) {
            throw new ServiceException("用户未登录");
        }
        else if (cookie != null) {
            user = userRepository.findUserByUsername(cookie.getValue());
        } else {
            throw new ServiceException("不存在该用户!");
        }
        return user;
    }

    public User getUserById(Integer id){
        User user = userRepository.getOne(id);
        return user;
    }

    public User getUserByUsername(String username){
        return userRepository.findUserByUsername(username);
    }
    public Integer updateUser(User user){

        Integer integer = userRepository.updateUser(user);
        return integer;
    }

    public Integer deleteUserById(Integer id){
        Integer integer = userRepository.deleteUserById(id);
        return integer;
    }

    public Integer addUser(User user){
//        userRepository.save(user);
        Integer integer = userRepository.addUser(user);
        return integer;
    }

    public Result updateUserPassword(HttpSession session, HttpServletRequest request, HttpServletResponse response, Integer id, String oldPassword, String newPassword){
        User oldUser = userRepository.findById(id).orElseThrow(() -> new ServiceException("用户ID错误!"));
        if (!oldUser.getPassword().equals(oldPassword)) {
            return ResultGenerator.genFailResult("原始密码错误!");
        }
        oldUser.setPassword(newPassword);
        userRepository.save(oldUser);
        //重新登录
        loginService.logout(request, response, session);
        return ResultGenerator.genSuccessResult();
    }
}
